﻿using System.Diagnostics;

namespace HHFileViewServer
{
    public class OfficeService : IService
    {
        private readonly ILogger<OfficeService> _logger;
        public OfficeService(ILogger<OfficeService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 文件转换
        /// </summary>
        /// <param name="fileInfo">文件信息</param>
        /// <returns></returns>
        public BaseFileInfo Conversion(BaseFileInfo fileInfo, string password)
        {
            // 检查LibreOffice文件真实性
            if (!File.Exists(ServerOp.ServerConfig.LibreOffice))
                throw new CustomException("LibreOffice安装路径不正确。");

            var libreOfficeFileInfo = new FileInfo(ServerOp.ServerConfig.LibreOffice);
            if (libreOfficeFileInfo.Name.ToLower() != "soffice.exe")
                throw new CustomException("LibreOffice安装路径不正确。");

            // 源文件地址
            string sourcePath = FileHelper.HandlePathByLibreOffice(fileInfo.AbsolutePath);
            var file = new FileInfo(sourcePath);
            if (file == null)
            {
                throw new CustomException($"需要预览的文件（{fileInfo.Name.Replace(fileInfo.Extension, "")}）不存在！");
            }
            // 目标文件夹地址
            string? targetPath = file.Directory?.FullName;
            using (Process process = new Process())
            {
                // 扩展名
                string ex = fileInfo.Extension.ToLower();
                // 如果是表格，默认转换为html
                bool isHtml = (ex == ".xls" || ex == ".xlsx");
                string extension = (isHtml ? ".html" : ".pdf");
                process.StartInfo.UseShellExecute = true;
                // 本地LibreOffice安装地址
                process.StartInfo.FileName = ServerOp.ServerConfig.LibreOffice;
                // LibreOffice转换命令
                process.StartInfo.Arguments = @$"soffice  --headless --invisible --convert-to {(isHtml ? "html" : "pdf")} {sourcePath}  --outdir {targetPath}";

                _logger.LogInformation("转换命令：" + process.StartInfo.Arguments);

                process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.UseShellExecute = false;
                process.Start();

                using (var sr = process.StandardOutput)
                {
                    while (!sr.EndOfStream)
                    {
                        _logger.LogInformation("转换结果：" + sr.ReadLine());
                        Console.WriteLine(sr.ReadLine());
                    }
                    if (!process.HasExited)
                    {
                        process.Kill();
                    }
                }
                process.Close();

                DirectoryInfo directoryInfo = new DirectoryInfo(ServerOp.ServerConfig.DownloadPath);

                // 判断对应文件夹下是否有对应文件
                var fileName = fileInfo.Name.Replace(fileInfo.Extension, extension);
                var filePath = targetPath + "/" + fileName;

                if (!File.Exists(filePath))
                    throw new CustomException($"文件（{fileInfo.Name.Replace(fileInfo.Extension, "")}）预览失败！");


                fileInfo.Path = Const.RelativePath(fileName);
                fileInfo.AbsolutePath = filePath;
                fileInfo.Extension = extension;
                fileInfo.FileType = isHtml ? FILETYPE.HTML : FILETYPE.PDF;
                return fileInfo;
            }
        }
    }
}
